package com.mar.tech.unify.bean;

import io.vertx.core.buffer.Buffer;
import io.vertx.core.http.HttpHeaders;
import io.vertx.core.http.HttpServerResponse;
import io.vertx.core.json.EncodeException;
import io.vertx.core.json.Json;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.RoutingContext;

/**
 * Description: 响应值的处理 .<br>
 *
 * @author m-xy
 *     Created By 2019/12/4 13:21
 */
public class Result {

  /**
   * 成功的响应，返回的 {@link HttpHeaders#CONTENT_TYPE} 标记为 [application/json; charset=utf-8].
   *
   * @param routingContext 上下文.
   * @param data           业务对象.
   */
  public static void ok(RoutingContext routingContext, Object data) {
    JsonObject result = new JsonObject();
    result.put("code", 0);
    result.put("data", data);
    json(routingContext, result);
  }

  /**
   * 失败的响应，返回的 {@link HttpHeaders#CONTENT_TYPE} 标记为 [application/json; charset=utf-8].
   *
   * @param routingContext 上下文.
   * @param code           业务异常编码.
   * @param message        业务异常描述.
   */
  public static void failed(RoutingContext routingContext, int code, String message) {
    JsonObject result = new JsonObject();
    result.put("code", code);
    result.put("message", message);
    json(routingContext, result);
  }

  /**
   * 失败的响应，返回的 {@link HttpHeaders#CONTENT_TYPE} 标记为 [application/json; charset=utf-8].
   *
   * @param routingContext 上下文.
   * @param message        业务异常描述.
   */
  public static void failed(RoutingContext routingContext, String message) {
    JsonObject result = new JsonObject();
    result.put("code", 400);
    result.put("message", message);
    json(routingContext, result);
  }

  /**
   * 将响应的 {@link HttpHeaders#CONTENT_TYPE} 标记为 [application/json; charset=utf-8].
   *
   * @param routingContext 上下文.
   * @param json           返回的JSON对象.
   */
  private static void json(RoutingContext routingContext, JsonObject json) {
    HttpServerResponse res = routingContext.response();
    if (json == null) {
      res.putHeader(HttpHeaders.CONTENT_TYPE, "application/json; charset=utf-8");
      res.end("null");
    } else {
      try {
        Buffer buffer = Json.encodeToBuffer(json);
        res.putHeader(HttpHeaders.CONTENT_TYPE, "application/json; charset=utf-8");
        res.end(buffer);
      } catch (EncodeException | UnsupportedOperationException e) {
        routingContext.fail(e);
      }
    }
  }
}
